<template>
  <a-card
    class="general-card"
    :title="smsSignFormData.id ? '修改签名' : '新增签名'"
    :bordered="false"
  >
    <a-form
      ref="formRef"
      :model="smsSignFormData.form"
      layout="horizontal"
      auto-label-width
    >
      <a-form-item field="signName" label="消息标题" :rules="[REQUIRED]">
        <a-input
          v-model="smsSignFormData.form.signName"
          placeholder="仅限2-12个字符，建议使用APP应用名称或是网站名/公司名"
          :style="{ width: '400px' }"
        />
      </a-form-item>
      <a-form-item field="signSource" label="签名来源" :rulese="[REQUIRED]">
        <a-select
          v-model="smsSignFormData.form.signSource"
          placeholder="请选择签名来源"
          :style="{ width: '400px' }"
        >
          <a-option :value="0">企业单位的全称或简称</a-option>
          <a-option :value="1">工信部备案网站的全称或简称</a-option>
          <a-option :value="2">App应用的全称或简称</a-option>
          <a-option :value="3">公众号或小程序的全称或简称</a-option>
          <a-option :value="4">电商平台店铺名的全称或简称</a-option>
          <a-option :value="5">商标名的全称或简称</a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="">
        <div class="tips">
          <p
            >签名来源选择工信部备案网站的全称或简称时，请在说明中添加网站域名，加快审核速度；</p
          >
          <p
            >如果选择APP应用的全程或简称或公众号或小程序的全程或简称时，则网站、APP、小程序或公众号必须已上线；</p
          >
        </div>
      </a-form-item>
      <a-form-item label="证明文件" class="form-item-pic">
        <a-upload
          list-type="picture-card"
          :headers="{ token: accessToken }"
          :action="uploadFile"
          :style="{ marginRight: '10px' }"
          :onSuccess="businessLicenseSuccess"
          :on-error="handleError"
          :limit="1"
          :file-list="businessLicenseList"
          @before-upload="beforeUpload"
          image-preview
        >
        </a-upload>
        <a-upload
          list-type="picture-card"
          :headers="{ token: accessToken }"
          :action="uploadFile"
          :onSuccess="licenseSuccess"
          :on-error="handleError"
          :limit="1"
          :file-list="licenseList"
          @before-upload="beforeUpload"
          image-preview
        >
        </a-upload>
      </a-form-item>
      <a-form-item label="">
        <div class="tips">
          <p
            >第一张为营业执照，第二张为授权委托书，请上传签名归属方的企事业单位的企业营业执照、组织机构代码证、税务登记证三证合一的证件及授权委托书</p
          >
          <p>支持jpg、png、gif、jpeg格式的图片，每张图片不大于2MB</p>
        </div>
      </a-form-item>
      <a-form-item field="remark" label="申请说明">
        <a-textarea
          v-model="smsSignFormData.form.remark"
          allow-clear
          :style="{ width: '400px' }"
        />
      </a-form-item>
      <a-form-item label="">
        <a-button @click="router.go(-1)" style="margin-right: 10px"
          >返回</a-button
        >
        <a-button type="primary" @click="signFormSubmit()">提交</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script setup lang="ts">
  import uploadFile from '@/api/index';
  import { PickTablePage } from '@pickmall/ui-v3-components';
  import { MethodsRule, ColumnsDataRule } from '@/types/global';
  import { ref, watch, reactive, onMounted } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { smsSignDetail, addSmsSign, editSmsSign } from '@/api/setting';
  import { useRoute, useRouter } from 'vue-router';
  import { VARCHAR255, REQUIRED, VARCHAR20, MOBILE } from '@/utils/validator';
  import store from '@/utils/storage';

  const fileFormat = ref<Array<string>>(['jpg', 'jpeg', 'png', 'gif', 'bmp']);
  // 携带toekn
  const accessToken = ref<string>(store.getAccessToken() || '');
  const route = useRoute();
  const router = useRouter();
  const formRef = ref<FormInstance>();
  const businessLicenseList = ref();
  const licenseList = ref();
  interface formInterface {
    id: any;
    form: {
      signName: string;
      signSource: string;
      businessLicense: string;
      license: string;
      [key: string]: any;
    };
  }
  const smsSignFormData: formInterface = reactive({
    id: '',
    form: {
      signName: '',
      signSource: '',
      businessLicense: '',
      license: '',
    },
  });
  // 上传成功回调
  const businessLicenseSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('上传成功');
      smsSignFormData.form.businessLicense = res.response.result;
    }
  };
  const licenseSuccess = (res: any) => {
    if (res.response.success) {
      Message.success('上传成功');
      smsSignFormData.form.license = res.response.result;
    }
  };
  // 上传失败回调
  const handleError: any = (err: never) => {
    Message.error('上传失败');
  };
  // 上传前校验
  const beforeUpload: any = (file: any) => {
    return new Promise((resolve, reject) => {
      if (
        !fileFormat.value.includes(
          file.name.split('.')[file.name.split('.').length - 1]
        )
      ) {
        reject(new Error('上传失败'));
        Message.error(`请选择 .jpg .jpeg .png .gif .bmp格式文件`);
      } else if (Number((file.size / 1024).toFixed(0)) > 1024) {
        reject(new Error('上传失败'));
        Message.error(`所选文件大小过大，不得超过1M`);
      } else {
        resolve(true);
      }
    });
  };

  // 新增/修改签名提交
  const signFormSubmit = async () => {
    const auth = await formRef.value?.validate();
    if (!auth) {
      // 校验签名来源
      if (smsSignFormData.form.signSource === '') {
        Message.error('请选择签名来源！');
        return;
      }
      // 校验证件信息
      if (
        !smsSignFormData.form.businessLicense ||
        !smsSignFormData.form.license
      ) {
        Message.error('请完善证件信息！');
        return;
      }
      if (smsSignFormData.id) {
        // 修改
        editSmsSign(smsSignFormData.form).then((res) => {
          if (res.data.success) {
            Message.success('修改成功！');
            router.back();
          }
        });
      } else {
        // 新增
        addSmsSign(smsSignFormData.form).then((res) => {
          if (res.data.success) {
            Message.success('添加成功！');
            router.back();
          }
        });
      }
    }
  };

  // 初始化数据
  const init = async (): Promise<any> => {
    const res = await smsSignDetail(smsSignFormData.id);
    if (res.data.success) {
      smsSignFormData.form = res.data.result;
      if (res.data.result) {
        // 证明文件
        businessLicenseList.value = res.data.result.businessLicense
          ? [{ url: res.data.result.businessLicense }]
          : [];
        licenseList.value = res.data.result.license
          ? [{ url: res.data.result.license }]
          : [];
        // businessLicenseList.value = [{url: "https://lilishop-oss.oss-cn-beijing.aliyuncs.com/8b6a3e9e8cff4fc1bdc6fb281fb551bc.jpg"}];
      }
    }
  };

  // 初始化
  onMounted(() => {
    smsSignFormData.id = route.query.id;
    if (smsSignFormData.id) {
      init();
    }
  });
</script>

<style scoped lang="less">
  .tips {
    p {
      margin: 0;
      color: #999;
      font-size: 12px;
      line-height: 20px;
    }
  }
  :deep(.form-item-pic .arco-form-item-content) {
    flex: 0;
  }
</style>
